#include "bootloader.h"
#include "flash.h"
/*private variables***********************************************************************/
pFunction Jump_To_Application;
static uint32_t JumpAddress;
/*private prototype function***********************************************************************/
static void bootloader_jump_to_app(uint32_t address);

void bootloader_check_firmware_update(void)
{
    firmware_info_t firmware_current;
    firmware_info_t firmware_new;
 
    SCB->VTOR = FLASH_BASE;
    /*current firmware info*/
    firmware_current.version_info = *(__IO uint32_t*)CURRENT_FIRMWARE_VERSION_INFO_ADDRESS; 
    /*new firmware info*/
    firmware_new.version_info = *(__IO uint32_t*)NEW_FIRMWARE_VERSION_INFO_ADDRESS; 
    
    if(firmware_new.version_info > firmware_current.version_info)
    {
        if(((*(__IO uint32_t*)NEW_FIRMWARE_ADDRESS) & 0x2FFE0000 ) == 0x20000000){
            /*erase current firmware*/
            flash_page_erase(CURRENT_FIRMWARE_VERSION_INFO_ADDRESS, 90);
            flash_page_write(CURRENT_FIRMWARE_VERSION_INFO_ADDRESS, (uint32_t*)NEW_FIRMWARE_VERSION_INFO_ADDRESS ,90);
        }
        
    }else{
        
    }   
     bootloader_jump_to_app(CURRENT_FIRMWARE_ADDRESS);
}

static void bootloader_jump_to_app(uint32_t address)
{
  /*check app address*/ 
  if(((*(__IO uint32_t*)address) & 0x2FFE0000 ) == 0x20000000)
		{
			//Jump to app start address to excute app, address + 4 means the start of vector table
   JumpAddress = *(__IO uint32_t*) (address + 4);
			Jump_To_Application = (pFunction) JumpAddress;
			//set app processor stack pointer
   __set_MSP(*(__IO uint32_t*) address);
			
   //jump to excute app
			Jump_To_Application();

  }
}



